package 可视化算法.排序算法可视化.插入排序可视化之近乎有序的数;

import java.awt.*;

public class AlgoVisualizer {

    private static int DELAY = 40;

    private InsertionSortData data;
    private AlgoFrame frame;

    public AlgoVisualizer(int sceneWidth, int sceneHeight, int N) {

        // 初始化数据
        data = new InsertionSortData(N, sceneHeight, InsertionSortData.Type.NearlyOrdered);

        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("插入排序算法可视化", sceneWidth, sceneHeight);
            new Thread(() -> {
                this.run();
            }).start();
        });
    }

    // 动画逻辑
    private void run() {

        this.setData(0, -1);
        for (int i = 0; i < data.N(); i++) {
            this.setData(i, i);
            for (int j = i; j > 0 && data.get(j) < data.get(j - 1); j--) {
                data.swap(j, j - 1);
                this.setData(i + 1, j - 1);
            }
        }
        this.setData(data.N(), -1);
    }

    private void setData(int orderedIndex, int currentIndex) {
        data.orderedIndex = orderedIndex;
        data.currentIndex = currentIndex;

        frame.render(data);
        AlgoVisHelper.pause(DELAY);
    }

    public static void main(String[] args) {

        int sceneWidth = 800;
        int sceneHeight = 800;
        // 排序元素的数量
        int N = 100;

        AlgoVisualizer vis = new AlgoVisualizer(sceneWidth, sceneHeight, N);
    }
}